package at.fpmedv.eclipse.helma.core;

import java.io.File;
import java.util.HashMap;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import at.fpmedv.eclipse.helma.util.ResourceContainer;

public class HelmaCorePlugin extends AbstractUIPlugin {

	private HelmaServer helmaServer;
	/**
	 * the plugin ID
	 */
	public static final String PLUGIN_ID = "at.fpmedv.eclipse.helma.core";

	/**
	 * the singelton
	 */
	private static HelmaCorePlugin plugin;

	public HelmaCorePlugin() {
		// nothing to do
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static HelmaCorePlugin getDefault() {
		return plugin;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}
	/**
	 * We can use this method to dispose of any system
	 * resources we previously allocated.
	 * @see IWorkbenchWindowActionDelegate#dispose
	 */
	public void dispose() {
		plugin = null;
/*			if (server != null) {
				server.stop();
				fireServerStopped();
				server = null;
			}
		}
		*/
		
	}

	/**
	 * getter for the Eclipse Helma Server wrapper, for lazy loading
	 * Creates one if no server can be found
	 * 
	 * @return Eclipse Helma Server wrapper Object
	 */
	public HelmaServer getServer() {
		if (helmaServer == null) {
			helmaServer = new HelmaServer();
		}
		return helmaServer;
	}
	
	/**
	 * helper method to log to the eclipse log
	 * 
	 * @param msg human readable message
	 */
	public void log(String msg) {
	      log(msg, null);
	}
	
	/**
	 * helper method to log to error log
	 * 
	 * @param msg human readable message
	 * @param e an exception
	 */
	public void log(String msg, Exception e) {
	   getLog().log(new Status(Status.ERROR, PLUGIN_ID, Status.ERROR, msg, e));
	}
	
	public void openResource(ResourceContainer rc) {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		String wRoot = workspace.getRoot().getLocation().toString();
		IPreferenceStore store = HelmaCorePlugin.getDefault().getPreferenceStore();
		String filePathString = rc.getResource().getName();

		IPath filePath = Path.fromOSString(filePathString);
		IWorkbench iWorkbench = PlatformUI.getWorkbench();
		IWorkbenchPage page = iWorkbench.getActiveWorkbenchWindow().getActivePage();
		IFile ifile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(filePath);
		boolean thereWasACoreException = false;
		// seems to be a worspace file
		if (ifile != null) {
			HashMap map = new HashMap();
		    map.put(IMarker.LINE_NUMBER, rc.getLineNumber());
		    
			try {
				IMarker marker = ifile.createMarker(IMarker.TEXT);
			    marker.setAttributes(map);
			    //page.openEditor(marker); //2.1 API
			   	IDE.openEditor(page, marker); //3.0 API
			   	marker.delete();
			} catch (CoreException e) {
				thereWasACoreException = true;
			}
		}
		if (ifile == null || thereWasACoreException) {
			// open File with absolute path
            File fileToOpen = new File(rc.getResource().getName());
            IFileStore fileStore = EFS.getLocalFileSystem().getStore(
                            fileToOpen.toURI());
            // open file from filestore
            try {
            	IEditorPart editorPart = IDE.openEditorOnFileStore(page, fileStore);
            	IEditorInput document= editorPart.getEditorInput();
                // org.eclipse.ui.texteditor.GotoLineAction
            } catch (PartInitException e1) {
            	HelmaCorePlugin.getDefault().log("Error opening Editor on filestore", e1);
            }
		}
	}
	
    public static Display getStandardDisplay() {
        Display display= Display.getCurrent();
        if (display == null) {
            display= Display.getDefault();
        }
        return display;     
    }
}
